package com.birdboot.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest  {
    private Socket socket;
    private String method;   //请求方式
    private String uri;      //抽象路径
    private String protocol; //协议版本
    private Map<String,String> headers =new HashMap<>();
    private String requestURI ;  //uri中？左侧的请求部分
    private String queryString;  //uri中？右侧的参数部分
    private Map<String,String > parameters = new HashMap<>();//保存每一组参数
    public HttpServletRequest(Socket socket)throws IOException ,EmptyRequestException{
        this.socket = socket;
        parseRequestLine();
        parseHeaders();
        parseContent();
    }
    public void parseRequestLine()throws IOException,EmptyRequestException{
        String line = readLine();
        if(line.isEmpty()){
            throw new EmptyRequestException();
        }
        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        parseUri();
        protocol = data[2];
    }
    private void parseUri(){
          String [] spilt = uri.split("\\?");
          if(spilt.length>=1){
              requestURI = spilt[0];
          }
          if(spilt.length==2){
              queryString = spilt[1];
              parseParameters(queryString);
          }
        System.out.println(queryString +"------------------\n");
        System.out.println(parameters +"------------------\n");
        System.out.println(requestURI +"------------------\n");

    }
    private void parseParameters(String line){
        String [] splitQuery = line.split("&");
        for (int i = 0; i < splitQuery.length; i++) {
            String [] splitParameters = splitQuery[i].split("=",2);
            parameters.put(splitParameters[0],splitParameters[1]);
                 /* String [] splitParameters = splitQuery[i].split("=");
                  if(splitParameters.length==1){
                      if(!splitParameters[0].isEmpty())parameters.put(splitParameters[0],null);
                  }
                  if(splitParameters.length==2){
                      if(!splitParameters[0].isEmpty())parameters.put(splitParameters[0],splitParameters[1]);
                  }*/
        }
    }

    public void parseHeaders()throws IOException{
        //2处理请求
        while (true){
            String line = readLine();
            if(line.isEmpty()){
                break;
            }
            System.out.println("消息头:"+line);
            String[] split = line.split(":\\s");
            if(split.length>=2){
                headers.put(split[0],split[1]);
            }else {
                System.out.println(split.length);
            }
        }
        System.out.println("headers:"+ headers);
    }
    //解析正文
    public void parseContent() throws IOException {
        if(headers.containsKey("Content-Length")){
            //获取正文长度
            int contentLength = Integer.parseInt(headers.get("Content-Length"));
            System.out.println("正文长度==========="+contentLength);

            byte [] data = new byte[contentLength];

                InputStream in = socket.getInputStream();
                in.read(data);
            if("application/x-www-form-urlencoded".equals(headers.get("Content-Type"))){
                String line = new String(data, StandardCharsets.ISO_8859_1);
                System.out.println("正文==============="+line);
                parseParameters(line);
            }
        }
    }

    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();//保存拼接后的一行字符串
        char cur='a',pre='a';//cur表示本次读取的字符  pre表示上次读取的字符
        while((d = in.read())!=-1){
            cur = (char)d;//将本次读取的字符赋值给cur
            if(pre==13 && cur==10){//判断上次是否读取的回车符,本次是否为换行符
                break;//若连续读取了回车+换行就停止读取(一行结束了)
            }
            builder.append(cur);
            pre=cur;//在读取下一个字符前,将本次读取的字符记作"上次读取的字符"
        }
        return builder.toString().trim();
    }

    public Socket getSocket() {
        return socket;
    }
    public String getMethod() {
        return method;
    }
    public String getUri() {
        return uri;
    }
    public String getProtocol() {
        return protocol;
    }
    public String getHeader(String key) {
        return headers.get(key);
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQueryString() {
        return queryString;
    }

    public String getParameters(String key) {
        return parameters.get(key);
    }
}
